const qs = require('qs')
import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

let appInfo
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    tokenTime: '',
    hotel: {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  // SET_NAME: (state, name) => {
  //   state.name = name
  // },
  SET_TOKEN_TIME: (state, tokenTime) => {
    state.tokenTime = tokenTime
  },
  SET_HOTEL: (state, hotel) => {
    state.hotel = hotel
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    appInfo = userInfo
    const data = {
      username: username.trim(),
      password: password
    }
    return new Promise((resolve, reject) => {
      login(qs.stringify(data)).then(response => {
        // const { data } = response
        const { access_token, expires_in } = response
        commit('SET_TOKEN', access_token)
        commit('SET_TOKEN_TIME', expires_in)
        setToken(access_token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        // const { data } = response
        const { name } = response
        if (!name) {
          // reject('Verification failed, please Login again.')
          reject('获取酒店信息失败,请重试！')
        }

        // const { name } = data

        // commit('SET_NAME', name)
        commit('SET_HOTEL', response)
        // commit('SET_AVATAR', avatar)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()

    //   logout(state.token).then(() => {
    //     removeToken() // must remove  token  first
    //     resetRouter()
    //     commit('RESET_STATE')
    //     resolve()
    //   }).catch(error => {
    //     reject(error)
    //   })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },

  // 重新获取令牌
  refreshToken({ commit }) {
    
    return new Promise(resolve => {
      removeToken()
      commit('RESET_STATE')
      actions.login({ commit }, appInfo)
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

